from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.json_response import SuccessResponse, ErrorResponse, DetailResponse
from dvadmin.utils.viewset import CustomModelViewSet

from ops.config.models import Basic


class BasicSerializer(CustomModelSerializer):
    """
    devops-序列化器
    """

    class Meta:
        model = Basic
        fields = '__all__'
        read_only_fields = ["id"]


class BasicViewSet(CustomModelViewSet):
    """
    devops接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    exclude_field = []
    queryset = Basic.objects.all()
    serializer_class = BasicSerializer
    extra_filter_backends = []
    permission_classes = []

    # 重写list方法
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True, request=request)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True, request=request)
        return SuccessResponse(data=serializer.data, msg="获取成功")

    # 重写create方法
    def create(self, request, *args, **kwargs):
        data = request.data
        type = data.get('type')

        # 循环传入的参数
        for k, v in data.items():
            if k != 'type':
                d = {
                    "type": type,
                    "name": k,
                    "value": v
                }

                # 尝试新增，失败则更新
                try:
                    obj = Basic(**d)
                    obj.save()
                except Exception as e:
                    print('配置项{0}存在，更新配置中...'.format(k))
                    obj1 = Basic.objects.get(name=k, type=type)
                    obj1.value = v
                    obj1.save()

        return DetailResponse(data=request.data, msg="新增成功")

